package zd.cornermemory.fragment.record;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import greendao.CjDao;
import zd.cornermemory.App;
import zd.cornermemory.R;
import zd.cornermemory.adapter.CjAdapter;
import zd.cornermemory.db.Cj;
import zd.cornermemory.db.GreenDaoManager;
import zd.cornermemory.ui.CjDetailActivity;
import zd.cornermemory.ui.CjPjDetailActivity;
import zd.cornermemory.ui.GraphicActivity;
import zd.cornermemory.utils.SpKey;
import zd.cornermemory.utils.Statistics;

/**
 * Created by zhud on 2019/4/29.
 */

public class TimeFragment extends Fragment implements View.OnClickListener{
    private CjAdapter      cjAdapter;
    private RecyclerView   rv;
    private List<Cj>       cjs;
    private TextView       zpj;
    private TextView       zpj_show;
    private TextView       min_text;
    private TextView       max_text;
    private TextView       group_text;
    private TextView       delete_text;
    private CjDao          cjDao;
    private RelativeLayout max_layout,min_layout,pj_layout;
    private Cj          minCj,maxCj;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_cj, container, false);
        cjDao =  GreenDaoManager.getInstance().getNewSession().getCjDao();
        cjs = new ArrayList<>();
        initViews(view);
        initData();
        return view;
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            currentPos = getActivity().getIntent().getExtras().getInt("currentPos");
            String[] scr = getResources().getStringArray(R.array.scr);
            group_text.setText(scr[currentPos]);
            List<Cj> cjss = App.getInstance().getAllCjMap().get(currentPos);
            if (cjss == null) {
                cjss = new ArrayList<>();
            }
            cjs.clear();
            cjs.addAll(cjss);
            Collections.sort(cjs, new Comparator<Cj>() {
                @Override
                public int compare(Cj cj, Cj t1) {
                    return (int)(t1.getId()-cj.getId());
                }
            });
            if (cjAdapter==null) {
                rv.setLayoutManager(new LinearLayoutManager(getActivity()));
                cjAdapter = new CjAdapter(getActivity(), cjs);
                rv.setAdapter(cjAdapter);
                cjAdapter.setOnClickItem(new CjAdapter.OnClickItem() {
                    @Override
                    public void onClick(int i) {
                        Intent intent = new Intent(getActivity(), CjDetailActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("bean",cjs.get(i));
                        bundle.putInt("position",cjs.size()-i);
                        bundle.putInt("currentPos",currentPos);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }

                    @Override
                    public void onDelete(int i) {
                        cjDao.delete(cjs.get(i));
                        List<Cj> mapList = App.getInstance().getAllCjMap().get(currentPos);
                        mapList.remove(cjs.get(i));
                        cjs.remove(i);
                        setMinMax();
                        Intent intent = new Intent(SpKey.DELETE_CJ);
                        getActivity().sendBroadcast(intent);
                    }
                });
            }

            setMinMax();
            if (cjAdapter!=null) {
                cjAdapter.notifyDataSetChanged();
            }
        }
    };

    public void initData() {
        mHandler.sendEmptyMessage(1);
    }
    private int mPosition;//传入详情页的


    private void initViews(View v) {
        rv = v.findViewById(R.id.listview);
        group_text = v.findViewById(R.id.group_text);
        zpj = v.findViewById(R.id.zpj);
        zpj_show = v.findViewById(R.id.zpj_show);
        min_text = v.findViewById(R.id.min);
        max_text = v.findViewById(R.id.max);
        min_layout = v.findViewById(R.id.min_layout);
        max_layout = v.findViewById(R.id.max_layout);
        pj_layout = v.findViewById(R.id.pj_layout);
        delete_text = v.findViewById(R.id.delete_text);
        min_layout.setOnClickListener(this);
        max_layout.setOnClickListener(this);
        pj_layout.setOnClickListener(this);
        delete_text.setOnClickListener(this);
    }

    private int mMinPosition;
    private int mMaxPosition;

    private void setMinMax() {

        List<Cj> tempList = new ArrayList<>();
        List<Cj> cjList = new ArrayList<>();
        tempList.addAll(cjs);
        Collections.sort(tempList, new Comparator<Cj>() {
            @Override
            public int compare(Cj cj, Cj t1) {
                return (int)(cj.getId()-t1.getId());
            }
        });
        for (Cj cj : tempList) {
            if (cj.getStatus() != 2) {
                cjList.add(cj);
            }
        }

        zpj.setText(getString(R.string.avg_all)+getString(R.string.left_k)+cjList.size()+"/"+cjs.size()+getString(R.string.right_k));
        long avg = 0;
        for (Cj cj : cjList) {
            avg += cj.getSingTime();
        }
        if (avg == 0) {
            zpj_show.setText("N/A");
            min_text.setText("N/A");
            max_text.setText("N/A");
            minCj = null;
            maxCj = null;
        }else{
            double a = avg/cjList.size();
            avg = Math.round(a);
            String avgStr = Statistics.timeToString((int) avg);
            zpj_show.setText(avgStr);
            minCj = Collections.min(cjList);

            maxCj = Collections.max(cjList);

            String minStr = Statistics.timeToString(minCj.getSingTime().intValue());
            if (minCj.getStatus() == 1) {
                minStr += "+";
            }

            String maxStr = Statistics.timeToString(maxCj.getSingTime().intValue());
            if (maxCj.getStatus() == 1) {
                maxStr += "+";
            }

            min_text.setText(minStr);
            max_text.setText(maxStr);
        }

    }

    private int currentPos;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.min_layout:
                if (minCj == null) {
                    return;
                }
                gotoDetail(true);
                break;
            case R.id.max_layout:
                if (maxCj == null) {
                    return;
                }
                gotoDetail(false);
                break;
            case R.id.pj_layout:
                if (minCj == null) {
                    return;
                }
                gotoPj();
                break;

            case R.id.txt_tj:
                Intent intent = new Intent(getActivity(), GraphicActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("currentPos",currentPos);

                bundle.putString("title",group_text.getText().toString());
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case R.id.delete_text:

                new AlertDialog.Builder(getActivity())
                        .setTitle(getString(R.string.alert))
                        .setMessage(getString(R.string.sure_delete))
                        .setCancelable(false)
                        .setNegativeButton(getString(R.string.cancel),null)
                        .setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                List<Cj> l = cjDao.queryBuilder().where(CjDao.Properties.Group.eq(currentPos)).list();
                                cjDao.deleteInTx(l);
                                List<Cj> mapList = App.getInstance().getAllCjMap().get(currentPos);
                                if (mapList != null) {
                                    mapList.clear();
                                }
                                cjs.clear();
                                setMinMax();
                                Intent intent = new Intent(SpKey.DELETE_CJ);
                                getActivity().sendBroadcast(intent);
                                dialog.dismiss();
                            }
                        }).show();

                break;
        }
    }

    private void gotoDetail(boolean isMin) {
        Intent intent = new Intent(getActivity(), CjDetailActivity.class);
        Bundle bundle = new Bundle();
        if (isMin) {
            bundle.putSerializable("bean",minCj);
            long minId = minCj.getId();
            for(int i=0;i<cjs.size();i++) {
                long currentId = cjs.get(i).getId();
                if (currentId == minId) {
                    mMinPosition = cjs.size()-i;
                    break;
                }
            }
            mPosition = mMinPosition;
        }else{
            bundle.putSerializable("bean",maxCj);
            long maxId = maxCj.getId();
            for(int i=0;i<cjs.size();i++) {
                long currentId = cjs.get(i).getId();
                if (currentId == maxId) {
                    mMaxPosition = cjs.size()-i;
                    break;
                }
            }
            mPosition = mMaxPosition;
        }
        bundle.putInt("position",mPosition);
        bundle.putInt("currentPos",currentPos);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private void gotoPj() {
        Intent intent = new Intent(getActivity(), CjPjDetailActivity.class);
        intent.putExtra("currentPos", currentPos);
        startActivity(intent);
    }

}
